package cn.tedu.tedutest02202.ex.handler;

import cn.tedu.tedutest02202.ex.ServiceException;
import cn.tedu.tedutest02202.web.JsonResult;
import cn.tedu.tedutest02202.web.ServiceCode;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.swing.*;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

@RestControllerAdvice
public class GlobalExceptionHandler extends RuntimeException{
    @ExceptionHandler
    public JsonResult<Void> handleServiceException(ServiceException e){
        return JsonResult.fail(e.getServiceCode(),e.getMessage());
    }

    @ExceptionHandler
    public JsonResult<Void> handleBindException(BindException e){
//        StringBuilder stringBuilder = new StringBuilder();
//        List<FieldError> fieldErrors = e.getFieldErrors();
//        for (FieldError fieldError : fieldErrors) {
//            stringBuilder.append(fieldError.getDefaultMessage());
//        }
        String message = e.getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERROR_BAD_REQUSET,message);
    }

    @ExceptionHandler
    public JsonResult<Void> handleConstraintViolationException(ConstraintViolationException e){
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        StringBuilder stringBuilder = new StringBuilder();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            stringBuilder.append(constraintViolation.getMessage());
        }
        return JsonResult.fail(ServiceCode.ERROR_BAD_REQUSET,stringBuilder.toString());
    }

    @ExceptionHandler
    public JsonResult<Void> handleServiceException(Throwable e){
        e.printStackTrace();
        return JsonResult.fail(ServiceCode.ERROR_BAD_REQUSET,"服务器忙，请稍后再试！");
    }

}
